from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
from mongoengine import *
from datetime import datetime

class historicalData(Document):
    symbol = StringField()
    date = DateTimeField()
    open = IntField()
    high = IntField()
    low = IntField()
    close = IntField()
    volume = IntField()
    barcount = IntField()
    average = IntField()
    updatetime = DateTimeField()
    addtime = DateTimeField()

class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

    # def contractDetails(self, reqId, contractDetails):
    #     print("contractDetails: ", reqId, " ", contractDetails)

    # def tickPrice(self, reqId, tickType, price, attrib):
    #     print("Tick Price. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Price:", price, end=' ')

    # def tickSize(self, reqId, tickType, size):
    #     print("Tick Size. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Size:", size)

    def mktDepthExchanges(self,depthMktDataDescriptions):
        print("depthMktData:",depthMktDataDescriptions)

    def historicalData(self, reqId, bar,):
        print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open, "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume, "Count:", bar.barCount, "WAP:", bar.average)
        newdata = locationuser(
            symbol = symbol,
            date = bar.date,
            open = bar.open,
            high = bar.high,
            low = bar.low,
            close = bar.close,
            volume = bar.volume,
            barcount = bar.barCount,
            average = bar.average,
            updatetime = datetime.now(),
            addtime = datetime.now()
            )
        newdata.save()

    def historicalTicksBidAsk(self,reqId,ticks,done):
        print("HistoricalTicksBidAsk:",reqId,"ticks:",ticks,"done:",done)

    def oneDayHistoricalData(self,date):
        contract = Contract()
        #king account
        contract.symbol = symbol
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange = "NASDAQ"


        ##js account
        # contract.symbol = "EUR"
        # contract.secType = "CASH"
        # contract.exchange = "IDEALPRO"
        # contract.currency = "USD"
        app.reqHistoricalData(1, contract, date, "1 D", "5 secs", "BID_ASK", 0, 1, False, [])

def main():
    global symbol
    symbol = "NIO"
    connect('brokers', host='localhost', port=27017)
    global app
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)

    # app.reqContractDetails(1, contract)
    # app.reqMarketDataType(4) # 4为延时数据，我的未认证账户测试用，认证账户注释掉
    # app.reqMktData(1, contract, "233", False, False, [])
    # app.reqMktDepthExchanges()
    # app.reqHistoricalData(1, contract, "", "1 D", "5 secs", "BID_ASK", 0, 1, False, [])
    # app.reqHistoricalTicks(1,contract,"","20210115 12:01:00",10,"Bid_Ask",0,True,[])
    app.oneDayHistoricalData("20210101 23:59:59") # 查询时间："YYYYMMDD HH:MM:SS" ，“”表示查询当天

    app.run()


if __name__ == "__main__":
    main()